﻿using System;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;

namespace Majoopic.Utility.Image
{
    /// <summary>
    /// Read the information of the image with the WPF Imaging library
    /// </summary>
    public class WPFImagingReader : BaseImageReader
    {
        #region Constructor
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="fileName"></param>
        public WPFImagingReader(string fileName)
            : base(fileName)
        {
            
        }
        
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="imageStream"></param>
        public WPFImagingReader(Stream imageStream)
            : base(imageStream)
        {           
        }
        #endregion

        #region Public  Methods
        /// <summary>
        /// Fill the information of a headerinformation object with the value inside the header picture.
        /// </summary>
        /// <param name="headerInformation"></param>
        public override void FillImageHeaderInformation(ImageHeaderInformation headerInformation)
        {
            BitmapDecoder bitmapDecoder = BitmapDecoder.Create(this.ImageStream, BitmapCreateOptions.None, BitmapCacheOption.None);
            BitmapMetadata imageMetadata = bitmapDecoder.Frames[0].Metadata as BitmapMetadata;

            headerInformation.Thumbnail = bitmapDecoder.Frames[0].Thumbnail;
            headerInformation.LensModel = imageMetadata.GetQuery(WPFImagingConstants.XMPLens) as string;
            headerInformation.CameraModel = imageMetadata.CameraModel;
            headerInformation.DateTaken = this.ConvertToDateTime(imageMetadata.GetQuery("/app1/ifd/exif/{ushort=36867}") as string);
            headerInformation.ExposureProgram = this.ConvertToShort(imageMetadata.GetQuery(WPFImagingConstants.EXIFExposureProgram));
            headerInformation.ExposureTime = this.ConvertToRational(imageMetadata.GetQuery(WPFImagingConstants.EXIFExposureTime));
            headerInformation.FlashMode = this.ConvertToShort(imageMetadata.GetQuery(WPFImagingConstants.EXIFFlashMode));
            headerInformation.FocalLenght = this.ConvertToRational(imageMetadata.GetQuery(WPFImagingConstants.EXIFFocalLenght));
            headerInformation.Height = bitmapDecoder.Frames[0].PixelHeight;
            headerInformation.Width = bitmapDecoder.Frames[0].PixelWidth;
            headerInformation.IsoSpeed = this.ConvertToShort(imageMetadata.GetQuery(WPFImagingConstants.EXIFISOSpeed));
            headerInformation.LensAperture = this.ConvertToRational(imageMetadata.GetQuery(WPFImagingConstants.EXIFFNumber));
        }        
        #endregion   
    }
}
